<?php
/*
 * @分销商城
 * @功能说明：订单接口
 * @更新说明：暂无更新
 * @文件名 OrderController.class.php
 * @编码 UTF-8
 * @创建时间 2016-1-22 下午5:22:01
 * @创建人 XING
 */

namespace wap\Controller;
class OrderController extends ApibaseController
{
    function __construct() {
        parent::__construct();
        $this->_CustEntityModel = D('CustEntity');
        $this->_CustAddressModel = D('CustAddress');
    }

    /*
	 * 分销商城_订单提交
	 * @date: 2016-3-14 下午3:45:47
	 * @editor: XING
	 */
    public function submit() {
        if (I('get.params')) {
            if (I('get.demo')) {
                session('loginUid', '231');
            }
            $getReceiveData = M('CustAddress')
                ->where(array('cust_id' => session('loginUid')))->select();
            foreach ($getReceiveData as $key => $value) {
                if ($value['is_default'] == 1) {
                    $dfaddress = $value;
                    break;
                }
            }
            $this->dfaddress = $dfaddress;
            $this->assign('getReceiveData', $getReceiveData);
            $this->assign('params', I('get.params'));
            $this->display('order/submit');
        }
    }

    /*
	 * 分销商城_提交订单
	 * @date: 2016-3-14 下午5:07:24
	 * @editor: XING
	 */
    public function sendOrder() {
        if (I('get.params')) {
            $orderId = date('YHd') . rand(10, 99) . date('sim') . rand(100, 999);
            $putCollect = '';
            $success = $priceNum = 0;
            $goodsCollect = explode(',', I('get.params'));
            $goodsMains = M('GoodsEntity');
            foreach ($goodsCollect AS $val) {
                $dataVal = explode('_', $val);
                $getGoodsMsg = M('GoodsEntity')->field('goods_id,goods_price,goods_title,goods_pic,goods_attr,goods_taxes_price,rete_column,rate,channel_price,hjprofit,byprofit,zsprofit,kcun,type')
                    ->where(array('goods_id' => $dataVal[0]))->find();
                //检查商品库存是否有效 商品库存 - 购买数量 >= 0
                if ($dataVal[1] > $getGoodsMsg['kcun']) {
                    dataFormat('', 0, '库存不足');
                }
                $orderCollect = M('OrderCollect');
                $orderCollect->startTrans();
                $getBizMsg = M('CustEntity')
                    ->field('cust_realname,salelevel')->where(array('cust_id' => $dataVal[2]))->find();
                $putCollect = $orderCollect->lock(true)->add(array(
                    'order_id'           => $orderId,
                    'goods_id'           => $dataVal[0],
                    'goods_title'        => $getGoodsMsg['goods_title'],
                    'goods_pic'          => $getGoodsMsg['goods_pic'],
                    'goods_taxes_price'  => $getGoodsMsg['goods_taxes_price'],
                    'rete_column'        => $getGoodsMsg['rete_column'],
                    'rate'               => $getGoodsMsg['rate'],
                    'pay_price'          => $getGoodsMsg['goods_price'],
                    'goods_attr'         => $getGoodsMsg['goods_attr'],
                    'type'               => $getGoodsMsg['type'],
                    'channel_price'      => $getGoodsMsg['channel_price'],
                    'profit'             => $getBizMsg['salelevel'] == '1' ? $getGoodsMsg['hjprofit'] : ($getBizMsg['salelevel'] == '2' ? $getGoodsMsg['byprofit'] : ($getBizMsg['salelevel'] == '3' ? $getGoodsMsg['zsprofit'] : 0)),
                    'biz_cust_id'        => $dataVal[2],
                    'biz_cust_salelevel' => $getBizMsg['salelevel'],
                    'biz_cust_realname'  => $getBizMsg['cust_realname'],
                    'pay_nums'           => $dataVal[1],
                    'add_at'             => time(),
                    'update_at'          => time()
                ));
                $putKucun = $goodsMains->lock(true)
                    ->where(array('goods_id' => $dataVal[0]))->setDec('kcun', $dataVal[1]);
                if ($putCollect && $putKucun) {
                    M('ShopCart')
                        ->where(array('goods_id' => $dataVal[0], 'cust_id' => session('loginUid'), 'biz_cust_id' => $dataVal[2]))->delete();
                    $success++;
                    $priceNum += $getGoodsMsg['goods_price'] * $dataVal[1];
                }
                $profitMain = M('GoodsProfit');
                //todo (普通商品)的收益以及总监团队商品收益
                if ($getGoodsMsg['type'] == '1') {
                    $data = array(
                        'goods_id'           => $getGoodsMsg['goods_id'],
                        'goods_title'        => $getGoodsMsg['goods_title'],
                        'goods_pic'          => $getGoodsMsg['goods_pic'],
                        'goods_attr'         => $getGoodsMsg['goods_attr'],
                        'goods_price'        => $getGoodsMsg['goods_price'],
                        'goods_nums'         => $dataVal[1],
                        'profit'             => $getBizMsg['salelevel'] == '1' ? $getGoodsMsg['hjprofit'] : ($getBizMsg['salelevel'] == '2' ? $getGoodsMsg['byprofit'] : ($getBizMsg['salelevel'] == '3' ? $getGoodsMsg['zsprofit'] : 0)),
                        'channel_price'      => $getGoodsMsg['channel_price'],
                        'cust_id'            => session('loginUid'),
                        'biz_cust_id'        => $dataVal[2],
                        'biz_cust_salelevel' => $getBizMsg['salelevel'],
                        'order_id'           => $orderId,
                        'is_profit'          => '0',
                        'add_at'             => time()
                    );
                    //总监收益
                    $zjId = (new ProfitController())->findZj($dataVal[2]);
                    if ($zjId) {
                        //经理升级的总监:40%, 店长升级的总监:20%
                        $data['zj_cust_id'] = $zjId;
                        $zjType = M('CustEntity')->getFieldByCustId($zjId, 'zj_type');
                        if ($zjType == '2') {
                            $data['zj_profit'] = number_format($data['profit'] * 0.4, 2, '.', '');
                        } else {
                            $data['zj_profit'] = number_format($data['profit'] * 0.2, 2, '.', '');
                        }
                    }
                    $profitMain->lock(true)->add($data);
                }
            }
            if ($success == count($goodsCollect)) {
                $orderMain = M('OrderEntity');
                $getAddress = M('CustAddress')
                    ->where(array('address_id' => I('get.address_id')))->find();
                if (!$getAddress) {
                    $orderCollect->rollback();
                    $profitMain->rollback();
                    dataFormat('', 0, '非法的地址参数');
                }
                $this->updCustMobile($getAddress['receive_mobile']);
                $discountNums = 0;
                $putOrderMain = $orderMain->lock(true)->add(array(
                    'order_id'         => $orderId,
                    'order_amount'     => $priceNum + I('get.taxes') + (I('get.express') ?: 0),
                    'order_pay'        => $priceNum + I('get.taxes') + (I('get.express') ?: 0) - $discountNums,
                    'order_taxes'      => I('get.taxes'),
                    'order_express'    => I('get.express') ?: 0,
                    'order_discount'   => $discountNums,
                    'order_status'     => '0',
                    'cust_id'          => session('loginUid'),
                    'nickname'         => session('loginNickname') ? session('loginNickname') : '',
                    'receive_name'     => $getAddress['receive_name'],
                    'receive_mobile'   => $getAddress['receive_mobile'],
                    'receive_identity' => $getAddress['receive_identity'],
                    'receive_provice'  => $getAddress['provice'],
                    'receive_city'     => $getAddress['city'],
                    'receive_address'  => $getAddress['provice'] . $getAddress['city'] . $getAddress['area'] . $getAddress['street'],
                    'add_at'           => time(),
                    'update_at'        => time()
                ));
                if ($putOrderMain) {
                    $orderMain->commit();
                    $orderCollect->commit();
                    $profitMain->commit();
                    $goodsMains->commit();
                    if (I('get.frFrom'))
                        redirect('/order/pay/?orderId=' . $orderId);
                    else
                        dataFormat($orderId);
                } else {
                    $orderCollect->rollback();
                    $profitMain->rollback();
                    $orderMain->rollback();
                    $goodsMains->rollback();
                    dataFormat('', 0, '数据流出错，请重试！');
                }
            } else {
                $orderCollect->rollback();
                $profitMain->rollback();
                $goodsMains->rollback();
                dataFormat('', 0, '订单参数缺失');
            }
        } else {
            dataFormat('', 0, '订单参数缺失');
        }
    }

    /*
	 * 分销商城_新增地址
	 * @date: 2016-3-14 下午5:30:20
	 * @editor: XING
	 */
    public function addAddress() {
        if (I('post.dosubmit')) {
            if (I('post.mobile')) {
                $this->updCustMobile(I('post.mobile'));
            }
            //检验身份证信息
            //A:18位 B:前17位位数字,最后一位(数字或'X/x')
            if (!preg_match('/^(([0-9]{15})|([0-9]{18})|([0-9]{17}(\d|X|x)))$/', I('post.identity'))) {
                dataFormat('', 0, '身份证信息有误');
            };
            $isTrue = $this->identification(I('post.name'), I('post.identity'));
            if (!$isTrue) {
                self::idVerify(I('post.name'), I('post.identity'));
            }

            $data = array(
                'receive_name'     => I('post.name'),
                'receive_identity' => I('post.identity'),
                'receive_mobile'   => I('post.mobile'),
                'provice'          => I('post.provice'),
                'city'             => I('post.city'),
                'area'             => I('post.area'),
                'street'           => I('post.street'),
                'update_at'        => time()
            );
            if (I('post.id')) {
                $putAddress = M('CustAddress')
                    ->where(array('address_id' => I('post.id')))->setField($data);
            } else {
                //检查是否有收货地址,如果没有收货地址则设置为默认
                $defAddress = M('CustAddress')->where(array('cust_id' => session('loginUid'), 'is_default' => '1'))->count();
                if ($defAddress < 1) {
                    $data['is_default'] = '1';
                }
                $data['cust_id'] = session('loginUid');
                $data['add_at'] = time();
                $putAddress = M('CustAddress')->add($data);
            }
            if ($putAddress) {
                dataFormat('', 1, '地址' . (I('post.id') ? '更新' : '添加') . '成功');
            } else {
                dataFormat('', 0, '操作失败');
            }
        } else {
            dataFormat('', 0, '参数缺失');
        }
    }

    /*
     * 分销商城_DT阿凡达数据身份证实名认证
     * @date: 2016-05-19 17:31:00
     * @editor: WENCUN
     * */
    public function idVerify($name, $identity) {
        $appKey = '02bce172142249eca774ac633a90640a';
        $rel = file_get_contents('http://api.avatardata.cn/IdCardCertificate/Verify?key=' . $appKey . '&realname=' . $name . '&idcard=' . $identity);
        $result = json_decode($rel, true);
        if ($result['error_code'] != '0' && $result['result']['code'] != '1000') {
            dataFormat('', 0, $result['result']['message'] ?: $result['reason']);
        } else {
            self::idSum();
        }
    }

    /*
     * 分销商城_身份证验证次数
     * @date: 2016-05-19 17:53:00
     * @editor: WENCUN
     * */
    public function idSum() {
        //缓存次数
        if ($num = S('id' . session('loginUid'))) {
            if ($num['num'] == 3) {
                dataFormat('', 0, '身份证验证超过次数');
            }
            if ($num['time'] == date('Y-m-d', time())) {
                S('id' . session('loginUid'), array('time' => date('Y-m-d', time()), 'num' => $num['num'] + 1));
            } else {
                S('id' . session('loginUid'), array('time' => date('Y-m-d', time()), 'num' => 1));
            }
        } else {
            S('id' . session('loginUid'), array('time' => date('Y-m-d', time()), 'num' => 1));
        }
    }

    /*
	 * 分销商城_订单支付
	 * @date: 2016-3-14 下午6:13:17
	 * @editor: XING
	 */
    public function pay() {
        if (I('get.orderId')) {
            $orderMains = M('OrderEntity')
                ->where(array('order_id' => I('get.orderId')))->find();
            if ($orderMains && !$orderMains['order_status']) {
                $this->assign('orderData', $orderMains);
                $this->display('order/pay');
            } else {
                $this->assign('msg', '无效订单');
                $this->display('saler/noauth');
            }
        } else {
            $this->assign('msg', '无效订单！');
            $this->display('saler/noauth');
        }
    }

    /*
     * 分销商城_全部订单
     * @date: 2016-1-22 下午5:22:22
     * @editor: XING
     */
    public function slist() {
        $page = I('post.page') ?: 1;
        $perpage = I('post.perpage') ?: 10;
        $status = I('get.status') != '' ?: I('post.status') != '' ?: '';
        $getList = M('OrderEntity')->where(array('cust_id' => session('loginUid'), 'order_type' => '0'));
        if (isset($status) && in_array($status, array('0', '1', '2', '3', '4', '5', '6', '-1'))) {
            $getList = $getList->where(array('order_status' => I('get.status')));
            $orderStatus = C('ostatus');
            $this->assign('stitle', $orderStatus[I('get.status')]);
        }
        $getList = $getList->order(array('add_at' => 'desc'))->page($page, $perpage)->select();
        $output = array();
        if ($getList) {
            foreach ($getList AS $val) {
                $goodsArr = array();
                $orderArr = array(
                    'order_id'           => $val['order_id'],
                    'order_at'           => date('Y-m-d H:i', $val['add_at']),
                    'money'              => $val['order_amount'],
                    'order_taxes'        => $val['order_taxes'],
                    'order_express'      => $val['order_express'],
                    'order_status'       => $val['order_status'],
                    'receive_name'       => $val['receive_name'],
                    'refund_expressnum'  => $val['refund_expressnum'],
                    'refund_expressname' => $val['refund_expressname']
                );
                $getOrderGoods = M('OrderCollect')
                    ->where(array('order_id' => $val['order_id']))->select();
                if ($getOrderGoods) {
                    $numPlus = 0;
                    foreach ($getOrderGoods AS $vals) {
                        $goodsArr[] = array(
                            'goods_id'          => $vals['goods_id'],
                            'goods_pic'         => transUrl($vals['goods_pic']),
                            'goods_title'       => trim($vals['goods_title']),
                            'goods_taxes_price' => trim($vals['goods_taxes_price']),
                            'rate'              => trim($vals['rate']),
                            'pay_price'         => trim($vals['pay_price']),
                            'pay_nums'          => trim($vals['pay_nums']),
                            'biz_cust_realname' => $vals['biz_cust_realname'],
                            'biz_cust_id'       => $vals['biz_cust_id'],
                            'goods_attr'        => $vals['goods_attr']
                        );
                        $numPlus += trim($vals['pay_nums']);
                    }
                    $orderArr['sum_nums'] = $numPlus;
                    $orderArr['goods_detail'] = $goodsArr;
                } else {
                    $orderArr['goods_detail'] = array();
                }

                $output[] = $orderArr;
            }
        }
        if (I('post.orderAjax')) {
            $html = '';
            if ($output) {
                foreach ($output as $key => $value) {
                    $html .= '<div class="dingdan-list">
							<div class="dingdan-list-zt"><a href="/order/odetail/orderId/' . $value['order_id'] . '">
							<span style="padding-right: 14px;">' . C('ostatus')[$value['order_status']] . '</span><i>订单号：</i>' . $value['order_id'] . '</a></div>
							<div class="dingdan-list-shr"><span>' . $value['order_at'] . '</span><i>收货人：</i>' . $value['receive_name'] . '</div>';
                    if ($value['goods_detail']) {
                        foreach ($value['goods_detail'] as $k => $v) {
                            $html .= '<div class="ck-tax"><ul>
            						<li class="dingdan-list-li1"><a href="/goods/detail/id/' . $v['goods_id'] . '/sek/' . I('get.sek') . '"><img src="' . transUrl($v['goods_pic']) . '" width="90%" height="90%"></a></li>
            						<li class="dingdan-list-li2"><a href="/goods/detail/id/' . $v['goods_id'] . '/sek/' . I('get.sek') . '">' . $v['goods_title'] . '<p>规格：' . $v['goods_attr'] . '</p></a></li>
            						<li class="dingdan-list-li3">¥ ' . $v['pay_price'] . '<p>×' . $v['pay_nums'] . '</p></li>
            						<span class="dingdan-tax" onclick="taxesClick(this)">税费：￥' . number_format($v['goods_taxes_price'] * $v['pay_nums'], 2, '.', '') . '</span>
        						  </ul><div class="tax">据国家政策规定，本品适用于跨境综合税：' . ($v['rate'] * 100) . '%</div>
        						  </div>';
                        }
                    }
                    $html .= '<div class="dingdan-list-order"><span>合计：<i>¥ ' . $value['money'] . '</i><br /><em>含运费：￥' . ($value['order_express'] ?: '0.00') . ' 税费￥' . $value['order_taxes'] . '</em></span>共 ' . $value['sum_nums'] . ' 件商品</div>';
                    $refundSth = $value['order_status'] == '6' ? 1 : 0;
                    $step1 = $value['order_status'] == '0' ? 1 : 0;
                    $refundBool = in_array($value['order_status'], array('1', '2', '3')) && (!$value['success_at'] || (time() - $value['success_at']) < getSysConfig('refundDays') * 24 * 3600) ? 1 : 0;
                    $html .= '<div class="dingdan-list-order2" ' . ($step1 || $refundBool || $refundSth || $value['order_status'] == '2' ? '' : 'style="display:none"') . '>';
                    if ($step1) {
                        $html .= '<a href="/order/pay/?orderId=' . $value['order_id'] . '">立即支付</a>
	       					  <a href="/order/cancle/orderId/' . $value['order_id'] . '" class="putCancle">取消订单</a>';
                    }
                    if ($refundBool) {
                        $getOemSum = M('OrderCollect')->where(array('order_id' => $value['order_id'], 'type' => '2'))->count();
                        if ($getOemSum < 1) {
                            $html .= '<a href="/order/refund/orderId/' . $value['order_id'] . '">申请退款</a>';
                        }
                    }
                    if ($value['order_status'] == '2') {
                        $html .= '<a class="putReceive" href="/order/receive/orderId/' . $value['order_id'] . '">确认收货</a>';
                    }
                    if ($refundSth) {
                        $html .= '<a href="/order/reback/orderId/' . $value['order_id'] . '">' . $value['refund_expressnum'] == '' ? '填写' : '查看' . '退货信息</a>';
                    }
                    $html .= '</div></div><center><hr style="border:1px solid #e5e5e5;width:95%"></center>';
                }
                echo json_encode(array('code' => '1', 'msg' => 'success', 'data' => $html, 'page' => $page));
                exit;
            } else {
                jsonRespons(0, '没有数据');
            }
        }
        $this->assign('dataout', $output);
        $this->assign('orderStatus', C('ostatus'));
        $this->display('order/list');
    }

    /*
	 * 分销商城_取消订单
	 * @date: 2016-3-16 上午11:32:58
	 * @editor: XING
	 */
    public function cancle() {
        if (I('get.orderId')) {
            $orderMain = M('OrderEntity');
            $setCancle = $orderMain->lock(true)->where(array('order_status' => '0', 'order_id' => I('get.orderId')))->setField(array(
                'order_status' => '-1',
                'update_at'    => time()
            ));
            if ($setCancle) {
                $goodsCollect = M('OrderCollect')
                    ->where(array('order_id' => I('get.orderId')))->select();
                if ($goodsCollect) {
                    $goodsMain = M('GoodsEntity');
                    foreach ($goodsCollect AS $vals) {
                        $putGoods = $goodsMain->lock(true)
                            ->where('goods_id = "' . $vals['goods_id'] . '"')->setInc('kcun', $vals['pay_nums']);
                        if ($putGoods) {
                            $goodsMain->commit();
                            $orderMain->commit();
                        } else {
                            $goodsMain->rollback();
                            $orderMain->rollback();
                        }
                    }
                } else {
                    $orderMain->rollback();
                }
                jsonRespons(1, '订单取消成功');
            } else {
                jsonRespons(0, '操作失败');
            }
        } else {
            jsonRespons(0, '非法参数请求');
        }
    }

    /*
     * 分销商城_确认收货
     * @date: 2016-3-16 上午11:32:58
     * @editor: XING
     */
    public function receive() {
        if (I('get.orderId')) {
            $orderMain = M('OrderEntity');
            $setReceive = $orderMain->field('order_id')
                ->where(array('order_status' => '2', 'order_id' => I('get.orderId')))->select();
            if ($setReceive) {
                foreach ($setReceive AS $val) {
                    $putOrder = $orderMain->lock(true)->where(array('order_id' => $val['order_id']))->setField(array(
                        'order_status' => '4',
                        'success_at'   => time(),
                        'update_at'    => time()
                    ));
                    if ($putOrder) {
                        $goodsProfit = M('GoodsProfit');
                        $putProfit = $goodsProfit->lock(true)
                            ->where('order_id = "' . $val['order_id'] . '" AND is_profit = 0')->setField(array(
                                'is_profit'  => '3',
                                'success_at' => time(),
                                'update_at'  => time()
                            ));
                        if ($putProfit) {
                            $goodsProfit->commit();
                            $orderMain->commit();
                            jsonRespons(1, '操作成功');
                        } else {
                            $goodsProfit->rollback();
                            $orderMain->rollback();
                            jsonRespons(0, '订单已确认收货 或 操作失败');
                        }
                    } else {
                        $orderMain->rollback();
                        jsonRespons(0, '订单已确认收货 或 操作失败');
                    }
                }
            } else {
                jsonRespons(0, '订单已确认收货 或 操作失败');
            }
        } else {
            jsonRespons(0, '非法参数请求');
        }
    }

    /*
	 * 分销商城_订单收货地址
	 * @date: 2016-3-16 下午3:27:09
	 * @editor: XING
	 */
    public function myaddress() {
        $getMyaddress = M('CustAddress')
            ->where(array('cust_id' => session('loginUid')))->order(array('is_default' => 'DESC'))->select();
        $this->assign('address', $getMyaddress);
        $this->display('order/address');
    }

    /*
	 * 分销商城_订单申请退款
	 * @date: 2016-3-17 上午11:39:03
	 * @editor: XING
	 */
    public function refund() {
        if (I('post.dosubmit')) {
            $checkOrder = M('OrderEntity')
                ->field('order_status,express_at,order_amount,order_pay')->where(array('order_id' => I('post.orderId')))->find();
            if ($checkOrder) {
                //&& (!$checkOrder['success_at'] || (time() - $checkOrder['success_at']) < 3*24*3600 )
                if (in_array($checkOrder['order_status'], array('1', '2', '3'))) {
                    $imgs = array();
                    if ($_FILES['files']) {
                        $imgs = upimgs($_FILES, 'files');
                    }
                    $putRefund = M('OrderEntity')
                        ->where(array('order_id' => I('post.orderId')))->setField(array(
                            'order_status'   => '5',
                            'refund_type'    => I('post.type') - 1,
                            'refund_content' => I('post.reason') ?: '',
                            'refund_mon'     => $checkOrder['order_pay'],
                            'refund_imgs'    => $imgs ? implode(',', $imgs) : '',
                            'update_at'      => time()
                        ));
                    if ($putRefund) {
                        $this->assign('msg', '您的退款已受理~');
                        $this->assign('url', '/order/slist');
                    } else {
                        $this->assign('msg', '操作失败');
                    }
                } else {
                    $this->assign('msg', '温馨提示：付款订单收货后' . getSysConfig('refundDays') . '天内才能申请退款~');
                }
            } else {
                $this->assign('msg', '无效订单');
            }
            $this->display('saler/noauth');
            exit;
        }
        if (I('get.orderId')) {
            $checkOrder = M('OrderEntity')
                ->field('order_status,express_at,order_amount')->where(array('order_id' => I('get.orderId')))->find();
            if ($checkOrder) {
                //&& (!$checkOrder['success_at'] || (time() - $checkOrder['success_at']) < 3*24*3600 )
                if (in_array($checkOrder['order_status'], array('1', '2', '3'))) {
                    $getCollectOrder = M('OrderCollect')
                        ->where(array('order_id' => I('get.orderId')))->select();
                    $this->assign('orderData', $checkOrder);
                    $this->assign('collectData', $getCollectOrder);
                    $this->display('order/refund');
                } else {
                    $this->assign('msg', '温馨提示：付款订单收货后3天内才能申请退款~');
                }
            } else {
                $this->assign('msg', '无效的订单参数');
            }
        } else {
            $this->assign('msg', '无效的订单参数');
        }
        $this->display('saler/noauth');
    }

    /*
     * 分销商城_订单填写退货物流信息
     * @date: 2016-3-17 上午11:39:03
     * @editor: XING
     */
    public function reback() {
        if (I('post.dosubmit')) {
            $checkOrder = M('OrderEntity')
                ->field('order_status,express_at,order_amount,order_pay')->where(array('order_id' => I('post.orderId')))->find();
            if ($checkOrder) {
                if ($checkOrder['order_status'] == '6') {
                    $putRefund = M('OrderEntity')
                        ->where(array('order_id' => I('post.orderId')))->setField(array(
                            'refund_expressname' => I('post.expressname') != '4' ? I('post.expressname') : I('post.strexpress'),
                            'refund_expressnum'  => I('post.expressnum'),
                            'update_at'          => time()
                        ));
                    if ($putRefund) {
                        $this->assign('msg', '退货信息提交成功~');
                        $this->assign('url', '/order/slist');
                    } else {
                        $this->assign('msg', '操作失败');
                    }
                } else {
                    $this->assign('msg', '温馨提示：无效订单状态');
                }
            } else {
                $this->assign('msg', '无效订单');
            }
            $this->display('saler/noauth');
            exit;
        }
        if (I('get.orderId')) {
            $checkOrder = M('OrderEntity')->where(array('order_id' => I('get.orderId')))->find();
            $refund_address = M('OrderEntity')->where(array('order_id' => I('get.orderId')))->getField('refund_address');
            $arr = explode(',', $refund_address);
            $get_arr = array();
            foreach ($arr as $key => $vo) {
                $get_arr[$key] = explode(':', $vo);
                unset($get_arr[$key][0]);
            }
            if ($checkOrder) {
                $getCollectOrder = M('OrderCollect')
                    ->where(array('order_id' => I('get.orderId')))->select();
                $this->assign('orderData', $checkOrder);
                $this->assign('refund_address', $get_arr);
                $this->assign('collectData', $getCollectOrder);
                if ($checkOrder['order_status'] == '6' && $checkOrder['refund_expressnum'] == '') {
                    $this->display('order/reback');
                    die();
                } elseif ($checkOrder['order_status'] == '6') {
                    $this->assign('ostatus', C('ostatus'));
                    $this->display('order/odetail');
                    die();
                } else {
                    $this->assign('msg', '温馨提示：非有效状态订单');
                }
            } else {
                $this->assign('msg', '无效的订单参数');
            }
        } else {
            $this->assign('msg', '无效的订单参数');
        }
        $this->display('saler/noauth');
    }

    /*
	 * 分销商城_订单详情页
	 * @date: 2016-3-24 下午2:20:42
	 * @editor: XING
	 */
    public function odetail() {
        $checkOrder = M('OrderEntity')->where(array('order_id' => I('get.orderId')))->find();
        if ($checkOrder) {
            $getCollectOrder = M('OrderCollect')
                ->where(array('order_id' => I('get.orderId')))->select();
            foreach ($getCollectOrder as $key => $value) {
                if ($value['express_num']) {
                    $express = array(
                        'express_name' => $value['express_name'],
                        'express_num'  => $value['express_num']
                    );
                    break;
                }
            }
            $this->assign('orderData', $checkOrder);
            $this->assign('collectData', $getCollectOrder);
            $this->assign('express', $express);
            $this->assign('ostatus', C('ostatus'));
            $this->display('order/odetail');
            die();
        } else {
            $this->assign('msg', '无效的订单参数');
            $this->display('saler/noauth');
        }
    }

    /*
	 * 分销商城_收货地址删除
	 * @date: 2016-3-17 下午1:26:47
	 * @editor: XING
	 */
    public function deladdress() {
        $putDelete = M('CustAddress')
            ->where(array('address_id' => I('get.id')))->delete();
        if ($putDelete) {
            $default = M('CustAddress')->where(array('cust_id' => session('loginUid'), 'is_default' => 1))->count();
            if ($default < 1) {
                M('CustAddress')->where(array('cust_id' => session('loginUid')))->order(array('update_at'))->limit(1)->setField(array('is_default' => 1, 'update_at' => time()));
            }
            jsonRespons(1, '地址删除成功');
        } else {
            jsonRespons(0, '操作失败');
        }
    }

    /*
     * 分销商城_设置默认收货地址
     * @date: 2016-04-08 10:32:00
     * @editor: WENCUN
     * */
    public function dfaddress() {
        $putUpdata = M('CustAddress')
            ->where(array('cust_id' => session('loginUid'), 'is_default' => 1))->setField('is_default', 0);
        $putDefault = M('CustAddress')
            ->where(array('address_id' => I('get.id')))->setField(array('is_default' => 1, 'update_at' => time()));
        if ($putDefault) {
            jsonRespons(1, '操作成功');
        } else {
            jsonRespons(0, '操作失败');
        }
    }

    /*
	 * 分销商城_我的账户
	 * @date: 2016-3-17 下午4:09:17
	 * @editor: XING
	 */
    public function account() {
        $this->display('order/cash');
    }

    /*
	 * 分销商城_调取帐号资金
	 * @date: 2016-3-17 下午3:22:06
	 * @editor: XING
	 */
    public function smoney() {
        if (I('get.type') && in_array(I('get.type'), array('1', '2', '3', '4'))) {
            if (I('get.enckey') == md5(I('get.type') . session('loginUid') . 'account')) {
                switch (I('get.type')) {
                    /*待结算金额*/
                    case '1':
                        $getProfitNums = M('GoodsProfit')
                            ->where(array('biz_cust_id' => session('loginUid')))->where('(is_profit = 0 OR is_profit = 3) AND pay_at > 0')->sum('profit * goods_nums');
                        //总监待结算金额
                        $zj = M('CustEntity')->where(array('cust_id' => session('loginUid'), 'salelevel' => '3'))->count();
                        if ($zj > 0) {
                            $zjProfit = M('GoodsProfit')->where(array('zj_cust_id' => session('loginUid')))->where('(is_profit = 0 OR is_profit = 3) AND pay_at > 0')->sum('zj_profit * goods_nums');
                            if ($zjProfit) {
                                $getProfitNums += $zjProfit;
                            }
                        }
                        break;
                    /*可提现金额*/
                    case '2':
                        $getProfitNums = M('CustBottler')
                            ->where(array('cust_id' => session('loginUid'), 'is_waste' => '0'))->sum('finance_money');
                        break;
                    /*提现中金额*/
                    case '3':
                        $getProfitNums = M('CustCash')
                            ->where(array('cust_id' => session('loginUid'), 'cash_status' => '0'))->where('is_check != -1')
                            ->sum('cash_money');
                        break;
                    /*已提现金额*/
                    case '4':
                        $getProfitNums = M('CustCash')
                            ->where(array('cust_id' => session('loginUid'), 'cash_status' => '1', 'is_check' => '1'))->sum('cash_money');
                        break;
                }

                echo json_encode(array('code' => '1', 'msg' => 'success', 'data' => $getProfitNums ?: '0.00'));
                exit;
            } else {
                jsonRespons(0, '非法请求');
            }
        } else {
            jsonRespons(0, '非法请求');
        }
    }



    /******************************************************************************************************************************************/
    /*
     * 分销商城_订单评价
     * @date: 2016-1-24 下午4:30:18
     * @editor: XING
     */
    public function judgeOrder() {
        if (I('post.order_id') && I('post.cust_id')) {
            if (I('post.judge_content') && in_array(I('post.judge_score'), array('1', '2', '3', '4', '5'))) {
                $getOrderStatus = M('OrderEntity')->field('order_status')
                    ->where(array('order_id' => I('post.order_id'), 'cust_id' => I('post.cust_id')))->find();
                if ($getOrderStatus['order_status'] == '3') {
                    $cbackCancle = M('OrderEntity')
                        ->where(array('order_id' => I('post.order_id')))->setField(array(
                            'order_status'  => '9',
                            'judge_content' => trim(I('post.judge_content')),
                            'judge_score'   => trim(I('post.judge_score')),
                            'update_at'     => time()
                        ));
                    if ($cbackCancle) {
                        dataFormat('', 1, '评价成功');
                    } else {
                        dataFormat('', 0, '操作失败');
                    }
                } else {
                    dataFormat('', 0, '无效订单');
                }
            } else {
                dataFormat('', 0, '参数有误');
            }
        } else {
            dataFormat('', 0, '参数有误');
        }
    }

    private function updCustMobile($mobile) {
        $affected = $this->_CustEntityModel->updateOneCust(array('cust_mobile' => $mobile), array('cust_id' => session('loginUid')));

        return $affected;
    }

    private function identification($name, $identification) {
        $return_flag = false;
        $address_info_identity = $this->_CustAddressModel->getOneAddress(array('receive_name'), array('receive_identity' => $identification));
        if (!$address_info_identity) {
            return $return_flag;
        }
        if ($address_info_identity && $address_info_identity['receive_name'] == $name) {
            $return_flag = true;
        } else {
            dataFormat('', 0, '身份证姓名错误');
        }
        return $return_flag;
    }
}